# -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import xlwt
import math
from .. import format_common
from openerp.tools.translate import _
import cStringIO
from openerp.osv import osv, fields
import os, time
import base64
from openerp.tools import float_round, float_is_zero, float_compare
import logging
from babel.numbers import format_decimal
_logger = logging.getLogger(__name__)
from xlwt import *

class summary_open_po_report(osv.osv_memory):
    _name = 'summary.open.po.report'
    _description = 'Summary Open PO Report'
    _columns = {
        'report_type': fields.selection([('summary_report', 'Summary Open PO Report'),('detail_report', 'Detail Open PO Report')],'Report Selection', required=True),
        'date_selection': fields.selection([('none_sel','None'),('date_sel', 'Date')],'Type Selection',required=True),
        'date_from': fields.date("From Date"),
        'date_to': fields.date("To Date"),
    }
    
    _defaults = { 
        'report_type': 'summary_report',          
        'date_selection': 'none_sel', 
    }
     
    
    def create_vat(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        datas = {'ids': context.get('active_ids', [])}
        datas['model'] = 'summary.open.po.report'
        datas['form'] = self.read(cr, uid, ids)[0]
        wizard = self.browse(cr, uid, ids[0], context)
        if wizard.report_type =='summary_report':
            return {
                'type': 'ir.actions.report.xml',
                'report_name': 'open.po.report',
                'datas': datas,
            }
        elif wizard.report_type =='detail_report':
            return {
                'type': 'ir.actions.report.xml',
                'report_name': 'open.detail.po.report',
                'datas': datas,
            }
    
    def _build_contexts(self, cr, uid, ids, data, report_type, context=None):
        if context is None:
            context = {}
        result = {}
        
        val_part = []
        val_part.append(('state','=','approved'))
        date_from = data['form']['date_from']
        date_to = data['form']['date_to']
        

        if data['form']['date_selection'] == 'date_sel' :
            if date_from and not date_to:
                val_part.append(('date_order','>=',str(date_from)))
            elif date_to and not date_from:
                val_part.append(('date_order','<=',str(date_to))) 
            elif date_to and date_from:
                val_part.append(('date_order','>=',str(date_from)))
                val_part.append(('date_order','<=',str(date_to)))

        result['val_part'] = val_part
        result['date_from'] = date_from
        result['date_to'] = date_to
        result['report_type'] = data['form']['report_type']

        return result
    
    def print_report(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        data = {}
        data['ids'] = context.get('active_ids', [])
        data['model'] = context.get('active_model', 'ir.ui.menu')
        data['form'] = self.read(cr, uid, ids, ['report_type', 'date_selection', 'date_from', 'date_to'], context=context)[0]
        for field in ['report_type', 'date_selection', 'date_from', 'date_to']:
            if isinstance(data['form'][field], tuple):
                data['form'][field] = data['form'][field][0]
                
        wizard = self.browse(cr, uid, ids[0], context)
        report_type = wizard.report_type   
         
        used_context = self._build_contexts(cr, uid, ids, data, report_type,  context=context)

        return self._get_tplines_xls(cr, uid, ids, used_context, report_type, context=context)
     
    def _get_tplines_xls(self, cr, uid, ids,data, type, context):
        form = data
        report_type = form['report_type']
        if not ids:
            ids = data['ids']
        if not ids:
            return []
         
        purchase_order_obj      = self.pool.get('purchase.order')
        stock_picking_obj     = self.pool.get('stock.picking')
        partner_obj     = self.pool.get('res.partner')
        company_obj = self.pool.get('res.company')
        currency_obj = self.pool.get('res.currency')
        user_obj = self.pool.get('res.users')
        purchase_orderline_obj    = self.pool.get('purchase.order.line')
        dp_obj = self.pool.get('decimal.precision')
        
        results1        = []
        result        = []
        balance_by_cur = {}
        val_part = form['val_part']
        date_from = form['date_from']
        date_to = form['date_to'] 
        
        workbook = xlwt.Workbook()
        M_header_tstyle = format_common.font_style(position='center', bold=1, border=3, fontos='black', font_height=300)
        report_tstyle = format_common.font_style(position='left', bold=1, fontos='black', font_height=190)
        report_tstyle1 = format_common.font_style(position='left', bold=1, fontos='black', font_height=180)
        header_tstyle = format_common.font_style(position='right', bold=1, fontos='black', font_height=180)
        header_tstyle_c = format_common.font_style(position='center', bold=1, fontos='black', font_height=180)
        header_tstyle_l = format_common.font_style(position='left', bold=1,border=1, fontos='black', font_height=180)
        header_tstyle_c_Top = format_common.font_style(position='center', bold=1, border=4, fontos='black', font_height=180)
        header_tstyle_c_Bottom = format_common.font_style(position='center', bold=1, border=3, fontos='black', font_height=180)
        header_tstyle_r = format_common.font_style(position='right', bold=1,  border=1,fontos='black', font_height=180)
        view_tstyle = format_common.font_style(position='left', fontos='black', font_height=180)
        view_tstyle_c = format_common.font_style(position='center', fontos='black', font_height=180)
        view_tstyle_l = format_common.font_style(position='left',border=1, fontos='black', font_height=180)
        view_tstyle_r = format_common.font_style(position='right', fontos='black', font_height=180)
        view_tstyle_r_b = format_common.font_style(position='right', bold=1, fontos='black', font_height=180)
        other_tstyle = format_common.font_style(position='left', fontos='black', font_height=180)
        other_tstyle_c = format_common.font_style(position='center', fontos='black', font_height=180)
        other_tstyle_r = format_common.font_style(position='right', fontos='black', font_height=180)
        text_tstyle = format_common.font_style(position='left', bold=1, border=1, fontos='black', font_height=180)
        text_tstyle1 = format_common.font_style(position='left', bold=1, fontos='black', font_height=220)
        text_tstyle2 = format_common.font_style(position='left', fontos='black', font_height=220)
        text_tstyle_c = format_common.font_style(position='center', bold=1, fontos='black', font_height=180)
        text_tstyle_l = format_common.font_style(position='left', bold=1, fontos='black', font_height=180)
        text_tstyle_r = format_common.font_style(position='right', bold=1, fontos='black', font_height=180)
        text_tstyle_r_closing = format_common.font_style(position='right', bold=1,border=7, fontos='black', font_height=180)
        text_tstyle_Top = format_common.font_style(position='left', bold=1, border=4, fontos='black', font_height=180)
        text_tstyle_Bottom = format_common.font_style(position='left', bold=1, border=3, fontos='black', font_height=180)
        text_tstyle_Top_r = format_common.font_style(position='right', bold=1, border=4, fontos='black', font_height=180)
        text_tstyle_Top_l = format_common.font_style(position='left', bold=1, border=4, fontos='black', font_height=180)
        text_tstyle_Top_r_r = format_common.font_style(position='right', bold=1, border=6, fontos='black', font_height=180)
        text_tstyle_Top_l_l = format_common.font_style(position='left', bold=1, border=6, fontos='black', font_height=180)
        text_tstyle_Bottom_r = format_common.font_style(position='right', bold=1, border=3, fontos='black', font_height=180)
        text_tstyle_TopBottom = format_common.font_style(position='left', bold=1, border=2, fontos='black', font_height=180)
        text_tstyle_TopBottom_r = format_common.font_style(position='right', bold=1, border=2, fontos='black', font_height=180)
        
         ## decimat format number
        dp_data = {}
        decimal_format = easyxf(num_format_str = '0.000000')
        dp_ids = dp_obj.search(cr, uid, [])
        print dp_ids
        for dp_id in dp_obj.browse(cr, uid, dp_ids, context=None) :
            dp_data[dp_id.name] = dp_id.digits
        
        #get data decimal precision by name 
        dp_account = dp_data['Account']
        dp_product_price = dp_data['Product Price']
        dp_product_uom = dp_data['Product Unit of Measure']
        
        #digit by account
        digits = int(math.pow(10, dp_account))
        digit_output = '#,##0.' + str(digits)[1:]

        currency_format = easyxf(num_format_str = digit_output)
        
        credit_limit_format = easyxf('font: bold 1; border: top thin')
        credit_limit_format.num_format_str = digit_output
        
        currency_ttl_format = easyxf('font: bold 1')
        currency_ttl_format.num_format_str = digit_output
        
        total_ttl_format_closing = easyxf('font: bold 1; border: top thick, bottom thick, left thick, right thick')
        total_ttl_format_closing.num_format_str = digit_output

        currency_ttl_format_tlrb_view = easyxf('border: top thin, bottom thin, left thin, right thin')
        currency_ttl_format_tlrb_view.num_format_str = digit_output
        
        currency_ttl_format_tlrb = easyxf('font: bold 1; border: top thick, bottom thick, left thick, right thick')
        currency_ttl_format_tlrb.num_format_str = digit_output
        
        
        #digit by unit price
        digits_up = int(math.pow(10, dp_product_price))
        digit_output_up = '#,##0.' + str(digits_up)[1:]

        unit_price_format = easyxf(num_format_str = digit_output_up)
        
        unit_price_ttl_format_tlrb_view = easyxf('border: top thin, bottom thin, left thin, right thin')
        unit_price_ttl_format_tlrb_view.num_format_str = digit_output_up
        
        #digit by unit of measure
        digits_uom = int(math.pow(10, dp_product_uom))
        digit_output_uom = '#,##0.' + str(digits_uom)[1:]

        unit_of_measure_format = easyxf(num_format_str = digit_output_uom)
        
        unit_of_measure_ttl_format_tlrb_view = easyxf('border: top thin, bottom thin, left thin, right thin')
        unit_of_measure_ttl_format_tlrb_view.num_format_str = digit_output_uom
        
        #### decimat format number
        
        if report_type == 'summary_report' :
            name_file = 'Summary Open PO.xls'
            sheet = workbook.add_sheet('Summary Open PO  XLS')
#             sheet.row(0).height = 350
        else :
            name_file = 'Detail Open PO.xls' 
            sheet = workbook.add_sheet('Detail Open PO  XLS')
#             sheet.row(0).height = 350
        
        row=0
        
        company_name = user_obj.browse(cr, uid, uid).company_id.name
        sheet.write_merge(row, row, 0, 6, company_name, report_tstyle1)
        
        #header titile
        if report_type == 'summary_report' :
            row+=1
            sheet.write_merge(row, row, 0, 6, 'Summary Open PO Report', report_tstyle1)
        else :
            row+=1
            sheet.write_merge(row, row, 0, 6, 'Detail Open PO Report', report_tstyle1)    
            
        #printed date
        user_ids = user_obj.search(cr, uid, [('id','=',uid)])
        if user_ids :
            tz = user_obj.browse(cr, uid, user_ids[0])
            tz_name = tz.tz
            user_name = tz.name
        os.environ['TZ'] = tz_name #set time zone secara otomatis tidak hard code
        time.tzset()
        row+=1
        sheet.write_merge(row, row, 0, 2, 'Printed date : ' + time.strftime("%Y/%m/%d") + '  Time : '+ time.strftime("%H:%M:%S"), report_tstyle1)
        sheet.write_merge(row, row, 3, 5, 'Printed by : ' +user_name , report_tstyle1)
        
        #search date
        if date_from and not date_to: 
            row+=1
            sheet.write_merge(row, row, 0, 6, 'Date : From ' + str(date_from), report_tstyle1) 
        elif date_to and not date_from: 
            row+=1
            sheet.write_merge(row, row, 0, 6, 'Date : Until ' + str(date_to), report_tstyle1)
        elif date_to and date_from: 
            row+=1
            sheet.write_merge(row, row, 0, 6, 'Date : ' + str(date_from) + ' - ' + str(date_to), report_tstyle1)
         
        if report_type == 'summary_report' :
            row+=1        
            sheet.row(row).height = 100
            sheet.write_merge(row, row, 0, 6, '', text_tstyle_c)
        #Header Name
        
        if report_type == 'summary_report' :
            row+=1
            sheet.write(row, 0, 'PO No.', header_tstyle_l)
            sheet.write(row, 1, 'Order Date', header_tstyle_l)
            sheet.write(row, 2, 'Supplier', header_tstyle_l)
            sheet.write(row, 3, 'Expected Date', header_tstyle_l)
            sheet.write(row, 4, 'Currency', header_tstyle_l)
            sheet.write(row, 5, 'Untaxed', header_tstyle_r)
            sheet.write(row, 6, 'Total', header_tstyle_r)
         
        
        
        #Column Width
        sheet.col(0).width = 256 * 16
        sheet.col(1).width = 256 * 20
        sheet.col(2).width = 256 * 35
        sheet.col(3).width = 256 * 18
        sheet.col(4).width = 256 * 10
        sheet.col(5).width = 256 * 18
        sheet.col(6).width = 256 * 18
         
        
        purchase_order_ids=purchase_order_obj.search(cr, uid,val_part)
         
        for purchase_orderr in purchase_order_obj.browse(cr, uid, purchase_order_ids, context=None):
            if purchase_orderr.shipped_rate >= 100:
                continue
            if purchase_orderr.all_service:
                continue
            cur_id_part = purchase_orderr.currency_id.id  
            val_ids_order_line = []
            
            if report_type == 'detail_report' :
                   
                purchase_order_line_ids=purchase_orderline_obj.search(cr, uid,[('order_id','=',purchase_orderr.id)])
                for purchase_order_line in purchase_orderline_obj.browse(cr, uid, purchase_order_line_ids, context=None) :
                     val_ids_order_line.append({
                       'name' : purchase_order_line.name,
                       'product_qty' : purchase_order_line.product_qty,
                       'currency_name': purchase_order_line.order_id.currency_id.name,
                       'price_unit': purchase_order_line.price_unit,
                       'subtotal': (purchase_order_line.product_qty * purchase_order_line.price_unit), 
                       })
                         
                val_ids_order_line = val_ids_order_line and sorted(val_ids_order_line, key=lambda val_res: val_res['name']) or []
                 
                
            
            results1.append({
                    'po_no' : purchase_orderr.name,
                    'date_order' :purchase_orderr.date_order,
                    'partner_id': purchase_orderr.partner_id.name,
                    'minimum_planned_date' : purchase_orderr.minimum_planned_date,
                    'currency_id' : purchase_orderr.currency_id.name,
                    'amount_untaxed' : purchase_orderr.amount_untaxed,
                    'amount_total' : purchase_orderr.amount_total,
                    'remark' : purchase_orderr.remark or ' ', 
                    'val_ids_order_line' : val_ids_order_line, 
                    })
                          
            if cur_id_part not in balance_by_cur:
                    balance_by_cur.update({cur_id_part : {
                             'total_untaxed' : (purchase_orderr.amount_untaxed),
                             'total_amount' : (purchase_orderr.amount_total),
                             }
                        })
            else:
                    res_currency_grouping = balance_by_cur[cur_id_part].copy()
                    res_currency_grouping['total_untaxed'] += (purchase_orderr.amount_untaxed)
                    res_currency_grouping['total_amount'] += (purchase_orderr.amount_total)
    
                    balance_by_cur[cur_id_part] = res_currency_grouping
        
        results1 = results1 and sorted(results1, key=lambda val_res: val_res['po_no']) or []
             
        for item in balance_by_cur.items():
            result.append({
                'cur_name' : currency_obj.browse(cr, uid, item[0]).name,
                'total_untaxed' : item[1]['total_untaxed'],
                'total_amount' : item[1]['total_amount'],
            })
                  
        result = result and sorted(result, key=lambda val_res: val_res['cur_name']) or []
                     
        
        
        for rs1 in results1:
            if report_type == 'detail_report' :
                
                row += 1
                sheet.row(row).height = 100
                sheet.write_merge(row, row, 0, 6, '', report_tstyle1)
                
                row+=1
                sheet.write(row, 0, 'PO No.', header_tstyle_l)
                sheet.write(row, 1, 'Order Date', header_tstyle_l)
                sheet.write(row, 2, 'Supplier', header_tstyle_l)
                sheet.write(row, 3, 'Expected Date', header_tstyle_l)
                sheet.write(row, 4, 'Currency', header_tstyle_l)
                sheet.write(row, 5, 'Untaxed', header_tstyle_r)
                sheet.write(row, 6, 'Total', header_tstyle_r)
                  
            row += 1 
            sheet.write(row, 0,str(rs1['po_no']), view_tstyle_l)
            sheet.write(row, 1,str(rs1['date_order']), view_tstyle_l)
            sheet.write(row, 2,str(rs1['partner_id']), view_tstyle_l)
            sheet.write(row, 3,str(rs1['minimum_planned_date']), view_tstyle_l)
            sheet.write(row, 4,rs1['currency_id'], view_tstyle_l)
            sheet.write(row, 5,rs1['amount_untaxed'], currency_ttl_format_tlrb_view)
            sheet.write(row, 6,rs1['amount_total'], currency_ttl_format_tlrb_view)
            
            if report_type == 'detail_report' :
                
                row += 1
                sheet.row(row).height = 100
                sheet.write_merge(row, row, 0, 6, '', report_tstyle1)
                
                row += 1 
                sheet.write(row, 2, 'Description', header_tstyle_l)
                sheet.write(row, 3, 'Quantity', header_tstyle_r)
                sheet.write(row, 4, 'Currency', header_tstyle_l)
                sheet.write(row, 5, 'Unit Price', header_tstyle_r)
                sheet.write(row, 6, 'Subtotal', header_tstyle_r)
            
                for rs3 in rs1['val_ids_order_line']:
                    row += 1 
                    sheet.write(row, 2, rs3['name'], view_tstyle_l)
                    sheet.write(row, 3, rs3['product_qty'], unit_of_measure_ttl_format_tlrb_view)
                    sheet.write(row, 4, rs3['currency_name'], view_tstyle_l)
                    sheet.write(row, 5, rs3['price_unit'], unit_price_ttl_format_tlrb_view)
                    sheet.write(row, 6, rs3['subtotal'], currency_ttl_format_tlrb_view) 
                
                row += 1 
                sheet.write_merge(row, row, 2, 6, 'Remark : ' + rs1['remark'])
                
                
        if report_type == 'summary_report' :
            for rs2 in result: 
                row += 1     
                sheet.write(row, 3,'Total', total_ttl_format_closing)
                sheet.write(row, 4,str(rs2['cur_name']), currency_ttl_format_tlrb)
                sheet.write(row, 5,rs2['total_untaxed'], currency_ttl_format_tlrb)
                sheet.write(row, 6,rs2['total_amount'], currency_ttl_format_tlrb)
                
        row += 1
        sheet.row(row).height = 100
        sheet.write_merge(row, row, 0, 6, '', report_tstyle1)
         
        row += 1
        sheet.write_merge(row, row, 0, 6, 'End of Report', text_tstyle_Top_l) 
        
        stream = cStringIO.StringIO()
        workbook.save(stream) 
        
        cr.execute(""" DELETE FROM output""")
        
        attach_id = self.pool.get('output').create(cr, uid, {'name': name_file, 'xls_output':base64.encodestring(stream.getvalue())})
        return {
                'name': _('Notification'),
                'context': context,
                'view_type': 'form',
                'view_mode': 'form',
                'res_model': 'output',
                'res_id':attach_id,
                'type': 'ir.actions.act_window',
                'target':'new'
                }  
         
summary_open_po_report()

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
